package com.supply.dl.utils;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;

import com.supply.dl.app.ApiService;
import com.supply.dl.app.http.BaseInfo;
import com.supply.dl.app.http.BaseObserver;
import com.supply.dl.app.http.HttpMethod;
import com.supply.dl.app.http.LoadingDialog;
import com.supply.dl.app.http.RxSchedulers;
import com.supply.dl.bean.FilePostResult;
import com.supply.dl.bean.JobAttachBean;

import java.io.File;
import java.util.ArrayList;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 提交文件助手
 * <p>
 * Author: tian <br>
 * Time: 2018/8/30 8:54
 */
public class FilePostUtil {

    /**
     * 提交文件
     *
     * @param context
     * @param files
     * @param onFilePostEndListener
     */
    public static void postFile(Context context, ArrayList<JobAttachBean> files, @NonNull final OnFilePostEndListener onFilePostEndListener) {

        int size = files.size();
        final int[] needPostCount = {size};

        Bundle bundle = new Bundle();
        bundle.putString("showMsg", "图片上传中...");

        final LoadingDialog loadingDialog = LoadingDialog.newInstance(bundle);
        loadingDialog.show(context);

        for (int i = 0; i < size; i++) {

            final JobAttachBean jab = files.get(i);
            File file = new File(jab.photoPath);

            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);

            MultipartBody.Part part = MultipartBody.Part.createFormData("uploadfile", file.getName(), requestFile);

            ApiService apiService = HttpMethod.getInstance().create(ApiService.class);

            apiService.uploadFile(part)
                    .compose(RxSchedulers.<BaseInfo<String>>compose(context))
                    .subscribe(new BaseObserver<FilePostResult>() {
                        @Override
                        public void onSuccess(BaseInfo<FilePostResult> baseInfo) {

                            if (baseInfo != null && baseInfo.getData() != null) {
                                jab.attachUrl = baseInfo.getData().getUrl();
                            }

                            needPostCount[0]--;

                            if (needPostCount[0] == 0) {
                                onFilePostEndListener.onFilePostEnd();
                                loadingDialog.dismiss();
                            }
                        }

                        @Override
                        public void onFailure(String msg) {
                            needPostCount[0]--;

                            if (needPostCount[0] == 0) {
                                onFilePostEndListener.onFilePostEnd();
                                loadingDialog.dismiss();
                            }
                        }
                    });
        }
    }


    public interface OnFilePostEndListener {
        void onFilePostEnd();
    }

}
